<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="白话JVM(1)-类的加载机制, van の blog">
    <meta name="description" content="类加载的过程咱首先回忆一张图：

我们编写的Java代码都是以 .java 为格式的文件，然后通过编译器编译成以 .class 结尾的字节码文件，最后通过java命令将字节码文件加载到JVM内存中。
下面就来详细分析一下字节码文件被加载到J">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>白话JVM(1)-类的加载机制 | van の blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.0.2"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">van の blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">van の blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/8.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">白话JVM(1)-类的加载机制</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/jvm/">
                                <span class="chip bg-color">jvm</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-08-21
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="类加载的过程"><a href="#类加载的过程" class="headerlink" title="类加载的过程"></a>类加载的过程</h2><p>咱首先回忆一张图：</p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/d29MHs"><img src="https://s1.ax1x.com/2020/08/25/d29MHs.png" alt="d29MHs.png"></a></p>
<p>我们编写的Java代码都是以 .java 为格式的文件，然后通过编译器编译成以 .class 结尾的字节码文件，最后通过java命令将字节码文件加载到JVM内存中。</p>
<p>下面就来详细分析一下字节码文件被加载到JVM中的过程，即类加载的全过程。</p>
<p>一般来说，类加载大致分为三个步骤：</p>
<p>加载、连接、初始化，其中连接又可以分为验证、准备、解析三个步骤，如下图所示：</p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/d2P7ng"><img src="https://s1.ax1x.com/2020/08/25/d2P7ng.md.png" alt="d2P7ng.md.png"></a></p>
<h3 id="1-加载"><a href="#1-加载" class="headerlink" title="1. 加载"></a>1. 加载</h3><p>这里首先要注意加载这个步骤和上面说到的类加载过程这两个名词的区别。加载只是类加载整个过程的其中一步而已。</p>
<p>在加载阶段，<strong>JVM会通过特定的类加载器去将字节码文件(.class文件)转化为二进制字节流加载到JVM内存中</strong>，然后通过这个二进制字节流解析出相关的类元信息，将其放入到方法区中，并且在堆中会生成一个java.lang.Class的对象，用来访问该类在方法区存放的元数据(这个详细会在java的内存结构中讲解)。</p>
<h3 id="2-连接"><a href="#2-连接" class="headerlink" title="2. 连接"></a>2. 连接</h3><ul>
<li><p>验证</p>
<p>验证阶段，说白了就是检查加载进来的类是不是合法的，是否符合虚拟机规范，万一别人随便篡改了文件咋整？</p>
<p>如下图所示，所有的class文件都是以 cafe babe 开头的。如果我们随意篡改，在类加载过程中肯定会报错的。</p>
<p>当然，验证阶段肯定还会有其他很多验证的规则，这里我们不过多赘述。</p>
<img src="https://s1.ax1x.com/2020/08/25/d2ZA4H.png" alt="d2ZA4H.png" style="zoom:50%;" />
</li>
<li><p>准备</p>
<p><strong>准备阶段，就是将类中定义的静态变量分配内存，并设置默认值</strong></p>
<p>看下面代码：</p>
<p>&lt;!–hexoPostRenderEscape:<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Main</span> <span class="token punctuation">&#123;</span></p>
<p>  <span class="token comment">//在加载阶段, a 会被赋默认值 0 ，int类型的默认值为 0 </span><br>  <span class="token keyword">static</span> <span class="token keyword">int</span> a <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span></p>
<p>  <span class="token comment">//在加载阶段， user会被赋默认值 null，引用类型的默认值为null</span><br>  <span class="token keyword">static</span> <span class="token class-name">User</span> user <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></p>
<p>  <span class="token comment">// d 为常量，在加载阶段会直接设置成真正的值 99</span><br>  <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> d <span class="token operator">=</span> <span class="token number">99</span><span class="token punctuation">;</span></p>
<p>  <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">complex</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span></p>
<pre><code>  &lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; b &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token number&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;token keyword&quot;&gt;int&lt;/span&gt; c &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;a &lt;span class=&quot;token operator&quot;&gt;-&lt;/span&gt; b&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;token operator&quot;&gt;*&lt;/span&gt; a&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;token keyword&quot;&gt;return&lt;/span&gt; c&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;</code></pre>
<p>  <span class="token punctuation">&#125;</span></p>
<p>  <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span></p>
<pre><code>  &lt;span class=&quot;token class-name&quot;&gt;Main&lt;/span&gt; main &lt;span class=&quot;token operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;token keyword&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;token class-name&quot;&gt;Main&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;

  main&lt;span class=&quot;token punctuation&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;token function&quot;&gt;complex&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;token punctuation&quot;&gt;;&lt;/span&gt;</code></pre>
<p>  <span class="token punctuation">&#125;</span></p>
</li>
</ul>
<p><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>:hexoPostRenderEscape–&gt;</p>
<p>​    这里有个需要注意的点，如果有<strong>静态变量被final修饰，此时静态变量会变成常量，在准备阶段会设置成真正的值，并放入常量池中</strong>。如上面代码中的 static final int d = 99</p>
<ul>
<li><p>解析</p>
<p><strong>解析阶段是将符号引用替换为直接引用的过程</strong></p>
</li>
</ul>
<p>这句话怎么理解呢？</p>
<p>首先，介绍 javap 命令，它可以配合一些参数对我们的代码进行反编译，下面,我们用 <strong>javap -v Main.class</strong> </p>
<p>输出如下信息：</p>
<p>我们重点关注 Constant pool ，即常量池，它左边的就是一个个符号引用，而右边最终对应的都是java的代码所对应的内存地址，即直接引用。在解析阶段，JVM会将一些符号引用转化为直接引用。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">D</span><span class="token operator">:</span>\project\web<span class="token operator">-</span>demo\target\classes\com\van\demo\sample<span class="token operator">></span>javap <span class="token operator">-</span>v <span class="token class-name">Main</span><span class="token punctuation">.</span><span class="token keyword">class</span>
<span class="token class-name">Classfile</span> <span class="token operator">/</span><span class="token class-name">D</span><span class="token operator">:</span><span class="token operator">/</span>project<span class="token operator">/</span>web<span class="token operator">-</span>demo<span class="token operator">/</span>target<span class="token operator">/</span>classes<span class="token operator">/</span>com<span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span><span class="token punctuation">.</span><span class="token keyword">class</span>
  <span class="token class-name">Last</span> modified <span class="token number">2020</span><span class="token operator">-</span><span class="token number">8</span><span class="token operator">-</span><span class="token number">25</span><span class="token punctuation">;</span> size <span class="token number">776</span> bytes
  MD5 checksum afc7085b9d65c9cc63c43d1fe64a0ef0
  <span class="token class-name">Compiled</span> from <span class="token string">"Main.java"</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample<span class="token punctuation">.</span><span class="token class-name">Main</span>
  minor version<span class="token operator">:</span> <span class="token number">0</span>
  major version<span class="token operator">:</span> <span class="token number">52</span>
  flags<span class="token operator">:</span> ACC_PUBLIC<span class="token punctuation">,</span> ACC_SUPER
<span class="token class-name">Constant</span> pool<span class="token operator">:</span>
   #<span class="token number">1</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">9.</span>#<span class="token number">33</span>         <span class="token comment">// java/lang/Object."&lt;init>":()V</span>
   #<span class="token number">2</span> <span class="token operator">=</span> <span class="token class-name">Fieldref</span>           #<span class="token number">3.</span>#<span class="token number">34</span>         <span class="token comment">// com/van/demo/sample/Main.a:I</span>
   #<span class="token number">3</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">35</span>            <span class="token comment">// com/van/demo/sample/Main</span>
   #<span class="token number">4</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">3.</span>#<span class="token number">33</span>         <span class="token comment">// com/van/demo/sample/Main."&lt;init>":()V</span>
   #<span class="token number">5</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">3.</span>#<span class="token number">36</span>         <span class="token comment">// com/van/demo/sample/Main.complex:()I</span>
   #<span class="token number">6</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">37</span>            <span class="token comment">// com/van/demo/sample/User</span>
   #<span class="token number">7</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">6.</span>#<span class="token number">33</span>         <span class="token comment">// com/van/demo/sample/User."&lt;init>":()V</span>
   #<span class="token number">8</span> <span class="token operator">=</span> <span class="token class-name">Fieldref</span>           #<span class="token number">3.</span>#<span class="token number">38</span>         <span class="token comment">// com/van/demo/sample/Main.user:Lcom/van/demo/sample/User;</span>
   #<span class="token number">9</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">39</span>            <span class="token comment">// java/lang/Object</span>
  #<span class="token number">10</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               a
  #<span class="token number">11</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">I</span>
  #<span class="token number">12</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               user
  #<span class="token number">13</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">User</span><span class="token punctuation">;</span>
  #<span class="token number">14</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token generics"><span class="token punctuation">&lt;</span>init<span class="token punctuation">></span></span>
  #<span class="token number">15</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
  #<span class="token number">16</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Code</span>
  #<span class="token number">17</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">LineNumberTable</span>
  #<span class="token number">18</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">LocalVariableTable</span>
  #<span class="token number">19</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token keyword">this</span>
  #<span class="token number">20</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span><span class="token punctuation">;</span>
  #<span class="token number">21</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               complex
  #<span class="token number">22</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">I</span>
  #<span class="token number">23</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               b
  #<span class="token number">24</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               c
  #<span class="token number">25</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               main
  #<span class="token number">26</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
  #<span class="token number">27</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               args
  #<span class="token number">28</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span>
  #<span class="token number">29</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">MethodParameters</span>
  #<span class="token number">30</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token generics"><span class="token punctuation">&lt;</span>clinit<span class="token punctuation">></span></span>
  #<span class="token number">31</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">SourceFile</span>
  #<span class="token number">32</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Main</span><span class="token punctuation">.</span>java
  #<span class="token number">33</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">14</span><span class="token operator">:</span>#<span class="token number">15</span>        <span class="token comment">// "&lt;init>":()V</span>
  #<span class="token number">34</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">10</span><span class="token operator">:</span>#<span class="token number">11</span>        <span class="token comment">// a:I</span>
  #<span class="token number">35</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               com<span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span>
  #<span class="token number">36</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">21</span><span class="token operator">:</span>#<span class="token number">22</span>        <span class="token comment">// complex:()I</span>
  #<span class="token number">37</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               com<span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">User</span>
  #<span class="token number">38</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">12</span><span class="token operator">:</span>#<span class="token number">13</span>        <span class="token comment">// user:Lcom/van/demo/sample/User;</span>
  #<span class="token number">39</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Object</span>
<span class="token punctuation">&#123;</span>
  <span class="token keyword">static</span> <span class="token keyword">int</span> a<span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token class-name">I</span>
    flags<span class="token operator">:</span> ACC_STATIC

  <span class="token keyword">static</span> com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample<span class="token punctuation">.</span><span class="token class-name">User</span> user<span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">User</span><span class="token punctuation">;</span>
    flags<span class="token operator">:</span> ACC_STATIC

  <span class="token keyword">public</span> com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample<span class="token punctuation">.</span><span class="token class-name">Main</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> ACC_PUBLIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> aload_0
         <span class="token number">1</span><span class="token operator">:</span> invokespecial #<span class="token number">1</span>                  <span class="token comment">// Method java/lang/Object."&lt;init>":()V</span>
         <span class="token number">4</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">7</span><span class="token operator">:</span> <span class="token number">0</span>
      <span class="token class-name">LocalVariableTable</span><span class="token operator">:</span>
        <span class="token class-name">Start</span>  <span class="token class-name">Length</span>  <span class="token class-name">Slot</span>  <span class="token class-name">Name</span>   <span class="token class-name">Signature</span>
            <span class="token number">0</span>       <span class="token number">5</span>     <span class="token number">0</span>  <span class="token keyword">this</span>   <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span><span class="token punctuation">;</span>

  <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">complex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">I</span>
    flags<span class="token operator">:</span> ACC_PUBLIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> iconst_2
         <span class="token number">1</span><span class="token operator">:</span> istore_1
         <span class="token number">2</span><span class="token operator">:</span> getstatic     #<span class="token number">2</span>                  <span class="token comment">// Field a:I</span>
         <span class="token number">5</span><span class="token operator">:</span> iload_1
         <span class="token number">6</span><span class="token operator">:</span> isub
         <span class="token number">7</span><span class="token operator">:</span> getstatic     #<span class="token number">2</span>                  <span class="token comment">// Field a:I</span>
        <span class="token number">10</span><span class="token operator">:</span> imul
        <span class="token number">11</span><span class="token operator">:</span> istore_2
        <span class="token number">12</span><span class="token operator">:</span> iload_2
        <span class="token number">13</span><span class="token operator">:</span> ireturn
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">15</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">16</span><span class="token operator">:</span> <span class="token number">2</span>
        line <span class="token number">18</span><span class="token operator">:</span> <span class="token number">12</span>
      <span class="token class-name">LocalVariableTable</span><span class="token operator">:</span>
        <span class="token class-name">Start</span>  <span class="token class-name">Length</span>  <span class="token class-name">Slot</span>  <span class="token class-name">Name</span>   <span class="token class-name">Signature</span>
            <span class="token number">0</span>      <span class="token number">14</span>     <span class="token number">0</span>  <span class="token keyword">this</span>   <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span><span class="token punctuation">;</span>
            <span class="token number">2</span>      <span class="token number">12</span>     <span class="token number">1</span>     b   <span class="token class-name">I</span>
           <span class="token number">12</span>       <span class="token number">2</span>     <span class="token number">2</span>     c   <span class="token class-name">I</span>

  <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> ACC_PUBLIC<span class="token punctuation">,</span> ACC_STATIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> <span class="token keyword">new</span>           #<span class="token number">3</span>                  <span class="token comment">// class com/van/demo/sample/Main</span>
         <span class="token number">3</span><span class="token operator">:</span> dup
         <span class="token number">4</span><span class="token operator">:</span> invokespecial #<span class="token number">4</span>                  <span class="token comment">// Method "&lt;init>":()V</span>
         <span class="token number">7</span><span class="token operator">:</span> astore_1
         <span class="token number">8</span><span class="token operator">:</span> aload_1
         <span class="token number">9</span><span class="token operator">:</span> invokevirtual #<span class="token number">5</span>                  <span class="token comment">// Method complex:()I</span>
        <span class="token number">12</span><span class="token operator">:</span> pop
        <span class="token number">13</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">24</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">26</span><span class="token operator">:</span> <span class="token number">8</span>
        line <span class="token number">27</span><span class="token operator">:</span> <span class="token number">13</span>
      <span class="token class-name">LocalVariableTable</span><span class="token operator">:</span>
        <span class="token class-name">Start</span>  <span class="token class-name">Length</span>  <span class="token class-name">Slot</span>  <span class="token class-name">Name</span>   <span class="token class-name">Signature</span>
            <span class="token number">0</span>      <span class="token number">14</span>     <span class="token number">0</span>  args   <span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span>
            <span class="token number">8</span>       <span class="token number">6</span>     <span class="token number">1</span>  main   <span class="token class-name">Lcom</span><span class="token operator">/</span>van<span class="token operator">/</span>demo<span class="token operator">/</span>sample<span class="token operator">/</span><span class="token class-name">Main</span><span class="token punctuation">;</span>
    <span class="token class-name">MethodParameters</span><span class="token operator">:</span>
      <span class="token class-name">Name</span>                           <span class="token class-name">Flags</span>
      args

  <span class="token keyword">static</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> ACC_STATIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">0</span>
         <span class="token number">0</span><span class="token operator">:</span> iconst_5
         <span class="token number">1</span><span class="token operator">:</span> putstatic     #<span class="token number">2</span>                  <span class="token comment">// Field a:I</span>
         <span class="token number">4</span><span class="token operator">:</span> <span class="token keyword">new</span>           #<span class="token number">6</span>                  <span class="token comment">// class com/van/demo/sample/User</span>
         <span class="token number">7</span><span class="token operator">:</span> dup
         <span class="token number">8</span><span class="token operator">:</span> invokespecial #<span class="token number">7</span>                  <span class="token comment">// Method com/van/demo/sample/User."&lt;init>":()V</span>
        <span class="token number">11</span><span class="token operator">:</span> putstatic     #<span class="token number">8</span>                  <span class="token comment">// Field user:Lcom/van/demo/sample/User;</span>
        <span class="token number">14</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">9</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">11</span><span class="token operator">:</span> <span class="token number">4</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">SourceFile</span><span class="token operator">:</span> <span class="token string">"Main.java"</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="3-初始化"><a href="#3-初始化" class="headerlink" title="3.初始化"></a>3.初始化</h3><p>这个阶段，<strong>会给静态变量赋为真正的值</strong>。如之前的代码中：</p>
<p>a 变量会赋值为5</p>
<p>user 变量会赋值为 new User() 的地址引用</p>
<p>此外，静态代码块也会在这个阶段运行。</p>
<p>需要注意的是，<strong>如果该类继承有父类，且父类没有初始化，则必须优先进行父类的初始化</strong>。</p>
<h2 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h2><h3 id="1-常见的类加载器"><a href="#1-常见的类加载器" class="headerlink" title="1. 常见的类加载器"></a>1. 常见的类加载器</h3><p>前面说到，加载的过程是靠特定的类加载器将字节码文件加载到JVM内存中的。那么，这里就来说说JVM到底有哪些类加载器，又有什么区别？</p>
<p>首先，绝大多数Java程序都会通过如下三种类加载器进行加载：</p>
<ul>
<li><p>BootStrapClassLoader(引导类加载器)：负责加载支撑JVM运行的位于JRE的lib目录下的核心类库，比如rt.jar、charsets.jar等</p>
</li>
<li><p>ExtClassLoader(扩展类加载器)：负责加载支撑JVM运行的位于JRE的lib目录下的ext扩展目录中的JAR类包</p>
</li>
<li><p>AppClassLoader(系统类加载器)：负责加载ClassPath路径下的类包，主要就是加载你自己写的那些类</p>
</li>
</ul>
<p>当然，我们还可以自定义类加载器，来加载我们指定路径下的类，这个后面再说。下面看这段代码：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestClassLoader</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ClassLoader</span> stringClassLoader <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"stringClassLoader = "</span> <span class="token operator">+</span> stringClassLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">ClassLoader</span> zipInfoClassLoader <span class="token operator">=</span> <span class="token class-name">ZipInfo</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"zipInfoClassLoader = "</span> <span class="token operator">+</span> zipInfoClassLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"zipInfoClassLoader parent= "</span> <span class="token operator">+</span> zipInfoClassLoader<span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token class-name">ClassLoader</span> testClassLoader <span class="token operator">=</span> <span class="token class-name">TestClassLoader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"testClassLoader = "</span> <span class="token operator">+</span> testClassLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"testClassLoader parent = "</span> <span class="token operator">+</span> testClassLoader<span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"testClassLoader parent parent = "</span> <span class="token operator">+</span> testClassLoader<span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//输出结果：</span>
stringClassLoader <span class="token operator">=</span> <span class="token keyword">null</span>
zipInfoClassLoader <span class="token operator">=</span> sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">Launcher</span>$<span class="token class-name">ExtClassLoader</span><span class="token annotation punctuation">@60215eee</span>
zipInfoClassLoader parent<span class="token operator">=</span> <span class="token keyword">null</span>
testClassLoader <span class="token operator">=</span> sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">Launcher</span>$<span class="token class-name">AppClassLoader</span><span class="token annotation punctuation">@18b4aac2</span>
testClassLoader parent <span class="token operator">=</span> sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">Launcher</span>$<span class="token class-name">ExtClassLoader</span><span class="token annotation punctuation">@60215eee</span>
testClassLoader parent parent <span class="token operator">=</span> <span class="token keyword">null</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>所以，我们能看出，<strong>BootstrapClassLoader由于是由C++程序创建的</strong>，所以在Java程序中无法显示，所以 String 的类加载器以及 ZipInfo 的父类加载器打印出来都是用null表示。</p>
<p>而我们本类的类加载器就是AppClassLoader，其父类加载器为ExtClassLoader。</p>
<h3 id="2-类加载器的创建过程"><a href="#2-类加载器的创建过程" class="headerlink" title="2. 类加载器的创建过程"></a>2. 类加载器的创建过程</h3><p><a target="_blank" rel="noopener" href="https://imgchr.com/i/d26ql4"><img src="https://s1.ax1x.com/2020/08/26/d26ql4.md.png" alt="d26ql4.md.png"></a></p>
<p>下面我们详细分析一下Launcher类的构造方法:</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">
<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">Launcher</span> launcher <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Launcher</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">private</span> <span class="token class-name">ClassLoader</span> loader<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">Launcher</span> <span class="token function">getLauncher</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> launcher<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token keyword">public</span> <span class="token class-name">Launcher</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span> var1<span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>：  var1 <span class="token operator">=</span> <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span><span class="token punctuation">.</span><span class="token function">getExtClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> var10<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InternalError</span><span class="token punctuation">(</span><span class="token string">"Could not create extension class loader"</span><span class="token punctuation">,</span> var10<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token operator">:</span>  <span class="token keyword">this</span><span class="token punctuation">.</span>loader <span class="token operator">=</span> <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">AppClassLoader</span><span class="token punctuation">.</span><span class="token function">getAppClassLoader</span><span class="token punctuation">(</span>var1<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> var9<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InternalError</span><span class="token punctuation">(</span><span class="token string">"Could not create application class loader"</span><span class="token punctuation">,</span> var9<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
 <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>先看(1),其实就是创建了ExtClassLoader，我们再来看一下它的getExtClassLoader()方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">ExtClassLoader</span> <span class="token keyword">extends</span> <span class="token class-name">URLClassLoader</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">//运用了双重检查锁的单例模式</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">volatile</span> <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span> instance<span class="token punctuation">;</span>

        <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span> <span class="token function">getExtClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">Class</span> var0 <span class="token operator">=</span> <span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">;</span>
                <span class="token keyword">synchronized</span><span class="token punctuation">(</span><span class="token class-name">Launcher</span><span class="token punctuation">.</span><span class="token class-name">ExtClassLoader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        instance <span class="token operator">=</span> <span class="token function">createExtClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>可以看到，<strong>getClassLoader() 是用了双重检查锁的单例模式来获取ExtClassLoader</strong>，这个很好理解，但是<strong>为什么它要对这个实例加上volatile关键字呢？</strong></p>
<p>其实主要是为防止指令重排的。</p>
<p>其中 instance = createExtClassLoader() 这一步是可能发生指令重排，而voletile 关键字通过内存屏障是可以保证有序性，禁止指令重排。</p>
<p>我们再来看(2):  this.loader = Launcher.AppClassLoader.getAppClassLoader(var1)</p>
<p>右边部分，是获取AppClassLoader,并且将上一步得到的ExtClassLoader实例传入，而这个ExtClassLoader最终会传入到ClassLoader类中，被赋予 this.parent = parent ,即说明在AppClassLoader创建过程中，上一步创建的扩展类加载器会被赋值给当前系统类加载器的parent属性。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">abstract</span> <span class="token keyword">class</span> <span class="token class-name">ClassLoader</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//....省略</span>
    <span class="token keyword">private</span> <span class="token class-name">ClassLoader</span><span class="token punctuation">(</span><span class="token class-name">Void</span> unused<span class="token punctuation">,</span> <span class="token class-name">ClassLoader</span> parent<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>parent <span class="token operator">=</span> parent<span class="token punctuation">;</span>
        <span class="token comment">//....省略</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//....省略</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>左边部分，是将当前Launcher类的ClassLoader属性值赋值为获取到的AppClassLoader。</p>
<p>打破双亲委派机制</p>
<p>实现一个自定义加载器，然后让一个类既可以在自定义类加载器中加载，也可以在应用类加载器中加载</p>
<h2 id="类加载器的双亲委派机制"><a href="#类加载器的双亲委派机制" class="headerlink" title="类加载器的双亲委派机制"></a>类加载器的双亲委派机制</h2><h3 id="1-双亲委派机制原理"><a href="#1-双亲委派机制原理" class="headerlink" title="1. 双亲委派机制原理"></a>1. 双亲委派机制原理</h3><p>类加载器在工作过程中，是依赖双亲委派机制。那么，什么是类加载器的双亲委派机制呢？</p>
<p>一个类最开始从AppClassLoader加载，首先AppClassLoader检查这个类它有没有加载过，如果加载过，直接返回，如果没有加载过，则委托它的父类加载ExtClassLoader去加载；ExtClassLoader也一样，首先检查这个类有没有加载过，如果加载过，直接返回，如果没有加载过，委托它的父类加载器BootstrapClassLoader去加载；BootStrapClassLoader首先也会检查这个类有没有加载过。如果已经加载过，直接返回。这里要注意，如果没有加载过，则它会自己尝试去加载，如果加载不到，则传递给子类加载器ExtClassLoader加载；同样，如果ExtClassLoader加载不到，则传递给AppClassLoader去加载。</p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/dfRbf1"><img src="https://s1.ax1x.com/2020/08/27/dfRbf1.png" alt="dfRbf1.png"></a></p>
<p>下面我们来看一下Java实现双亲委派机制的源码，Java双亲委派机制的源码实现是在java.lang.ClassLoader#loadClass()方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">,</span> <span class="token keyword">boolean</span> resolve<span class="token punctuation">)</span>
       <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span>
   <span class="token punctuation">&#123;</span>
       <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token function">getClassLoadingLock</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

           <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token operator">:</span>首先当前类加载器会去检查有没有加载过这个类
           <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> c <span class="token operator">=</span> <span class="token function">findLoadedClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
           <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token operator">:</span>如果没有加载过，c<span class="token operator">=</span><span class="token keyword">null</span><span class="token punctuation">,</span>进入下面逻辑
           <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
               <span class="token keyword">long</span> t0 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
               <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                   <span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token operator">:</span>判断当前类加载器的父类加载器是不是<span class="token keyword">null</span><span class="token punctuation">,</span>如果不是<span class="token keyword">null</span>，则让父类加载器调用loadClass方法加载
                   <span class="token keyword">if</span> <span class="token punctuation">(</span>parent <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                       c <span class="token operator">=</span> parent<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                   <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token operator">:</span>如果当前类加载器的父类加载器为boostrapClassLoder，则走这个里的逻辑（主要因为bootstrapClassLoader是由<span class="token class-name">C</span><span class="token operator">++</span>程序创建，无法在java显示，只能为<span class="token keyword">null</span>）
                       c <span class="token operator">=</span> <span class="token function">findBootstrapClassOrNull</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                   <span class="token punctuation">&#125;</span>
               <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                   <span class="token comment">// ClassNotFoundException thrown if class not found</span>
                   <span class="token comment">// from the non-null parent class loader</span>
               <span class="token punctuation">&#125;</span>
            <span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token operator">:</span>如果一直委托到bootstrapClassLoader还加载不到，则向下传递，由每一层类加载器调用<span class="token function">findClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span>方法，自己去加载，如果加载不到，返回<span class="token keyword">null</span>，继续向下传递
               <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                   <span class="token comment">// If still not found, then invoke findClass in order</span>
                   <span class="token comment">// to find the class.</span>
                   <span class="token keyword">long</span> t1 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                   c <span class="token operator">=</span> <span class="token function">findClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>

                   <span class="token comment">//......</span>
               <span class="token punctuation">&#125;</span>
           <span class="token punctuation">&#125;</span>
           <span class="token comment">//......</span>
           <span class="token keyword">return</span> c<span class="token punctuation">;</span>
       <span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>那为什么要设计双亲委派机制呢？</p>
<ol>
<li><p>防止类的重复加载</p>
<p>当类加载器向上委托的之前，都会检查一下自己是否已经加载过，如果加载过，就直接返回。这样就避免了类的重复加载。那么可能有人会问，为什么不直接从顶层的BootstrapClassLoader加载呢？其实原因还是这个。因为我们在使用的时候，大部分都是要加载自己写的代码（即类路径下的代码），如果每次都从顶层加载，这样无疑是浪费效率的。而如果用双亲委派机制，只有在第一次加载的时候，会从AppClassLoader向上委托，最后由BootstrapClassLoader向下一层层传递最后由AppClassLoader自己加载。后面再加载就会直接从AppClassLoader返回。</p>
</li>
<li><p>防止核心API被篡改</p>
<p>这个很好理解。比如我们写一个路径和类名和java中核心包中都一样的类，然后去加载，肯定会加载失败。</p>
</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">java<span class="token punctuation">.</span>lang</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">String</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//输出信息：</span>
错误<span class="token operator">:</span> 在类 java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span><span class="token class-name">String</span> 中找不到 main 方法<span class="token punctuation">,</span> 请将 main 方法定义为<span class="token operator">:</span>
   <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span>
否则 <span class="token class-name">JavaFX</span> 应用程序类必须扩展javafx<span class="token punctuation">.</span>application<span class="token punctuation">.</span><span class="token class-name">Application</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="2-自定义类加载器"><a href="#2-自定义类加载器" class="headerlink" title="2. 自定义类加载器"></a>2. 自定义类加载器</h3><p><a target="_blank" rel="noopener" href="https://imgchr.com/i/df4zvt"><img src="https://s1.ax1x.com/2020/08/27/df4zvt.png" alt="df4zvt.png" style="zoom: 67%;" /></a></p>
<p>首先我们来看下类加载器的继承关系，可以看到，AppClassLoader和ExtClassLoader最终都继承自ClassLoader。</p>
<p>那么，我们自定义的类加载器，也要继承自ClassLoader，然后重写 findClass() 方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">FileInputStream</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">InvocationTargetException</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">Method</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClassLoaderTest</span> <span class="token punctuation">&#123;</span>


    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">MyClassLoader</span> <span class="token keyword">extends</span> <span class="token class-name">ClassLoader</span><span class="token punctuation">&#123;</span>

        <span class="token keyword">private</span> <span class="token class-name">String</span> classPath<span class="token punctuation">;</span>

        <span class="token keyword">public</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token class-name">String</span> classPath<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>classPath <span class="token operator">=</span> classPath<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">private</span> <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">loadByte</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
            name <span class="token operator">=</span> name<span class="token punctuation">.</span><span class="token function">replaceAll</span><span class="token punctuation">(</span><span class="token string">"\\."</span><span class="token punctuation">,</span> <span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">FileInputStream</span> fis <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileInputStream</span><span class="token punctuation">(</span>classPath <span class="token operator">+</span> <span class="token string">"/"</span> <span class="token operator">+</span> name
                    <span class="token operator">+</span> <span class="token string">".class"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">int</span> len <span class="token operator">=</span> fis<span class="token punctuation">.</span><span class="token function">available</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> data <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">byte</span><span class="token punctuation">[</span>len<span class="token punctuation">]</span><span class="token punctuation">;</span>
            fis<span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
            fis<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> data<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">//重写findClass()方法</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">findClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span> <span class="token punctuation">&#123;</span>

            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> data <span class="token operator">=</span> <span class="token function">loadByte</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">//defineClass将一个字节数组转为Class对象，这个字节数组是class文件读取后最终的字节数组。</span>
                <span class="token keyword">return</span> <span class="token function">defineClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> data<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> data<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>


        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>

        <span class="token class-name">MyClassLoader</span> myClassLoader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token string">"d:/test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> aClass <span class="token operator">=</span> myClassLoader<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token string">"com.van.demo.Test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">ClassLoader</span> classLoader <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"classLoader = "</span> <span class="token operator">+</span> classLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Object</span> obj <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Method</span> method <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">getDeclaredMethod</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        method<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>



    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Test</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"用自定义类加载器加载的"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>将Test.java类编译后放到自定义类加载器的指定路径：</p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/dfIisx"><img src="https://s1.ax1x.com/2020/08/27/dfIisx.md.png" alt="dfIisx.md.png"></a></p>
<p>然后运行MyClassLoaderTest的main()方法，我们发现，输出的结果竟然和预期的不一样：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">classLoader <span class="token operator">=</span> sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">Launcher</span>$<span class="token class-name">AppClassLoader</span><span class="token annotation punctuation">@18b4aac2</span>
用自定义类加载器加载的<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<p>它怎么没有用的是自定义的类加载器，而是用AppClassLoader呢？</p>
<p>Zzzz，其实这是因为双亲委派机制的原因。因为我们在写Test这个类是在当前MyClassLoaderTest类的classpath下写的，然后复制到了我们自定义类加载器的指定路径下。</p>
<p>当然，这个要说个知识点：<strong>自定义类加载器的父类加载器默认都会是AppClassLoader</strong>。</p>
<p>所以，当我们加载Test类的时候，自定义类加载器会向上委托，然后由于BootstrapClassLoader和ExtClassLoader都加载不到，所以到了AppClassLoader加载，但是AppClassLoader的classpath路径下有这个类啊。所以直接由AppClassLoader加载了。</p>
<p>要解决这个问题也很好办，直接将classpath路径下的这个类的字节码文件删了就OK了。再次运行，结果如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">classLoader <span class="token operator">=</span> com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample<span class="token punctuation">.</span><span class="token class-name">MyClassLoaderTest</span>$<span class="token class-name">MyClassLoader</span><span class="token annotation punctuation">@7adf9f5f</span>
用自定义类加载器加载的<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>可以看到当前类的类加载器就是我们自定义的类加载器了</p>
<p>留一个问题：<strong>自定义类加载器为什么它的父类加载器是AppClassLoader呢？看源码</strong></p>
<h3 id="3-打破双亲委派机制"><a href="#3-打破双亲委派机制" class="headerlink" title="3. 打破双亲委派机制"></a>3. 打破双亲委派机制</h3><p>由上面的分析可知，双亲委派机制的实现主要是依赖于 java.lang.ClassLoader类的 loadClass()方法，那么，打破双亲委派机制，自然是改写它的loadClass()方法。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">FileInputStream</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">InvocationTargetException</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">Method</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClassLoaderTest</span> <span class="token punctuation">&#123;</span>


    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">MyClassLoader</span> <span class="token keyword">extends</span> <span class="token class-name">ClassLoader</span><span class="token punctuation">&#123;</span>

        <span class="token keyword">private</span> <span class="token class-name">String</span> classPath<span class="token punctuation">;</span>

        <span class="token keyword">public</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token class-name">String</span> classPath<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>classPath <span class="token operator">=</span> classPath<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">//重写loadClass()方法，打破双亲委派机制</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">,</span> <span class="token keyword">boolean</span> resolve<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span> <span class="token punctuation">&#123;</span>

            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token function">getClassLoadingLock</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// First, check if the class has already been loaded</span>
                <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> c <span class="token operator">=</span> <span class="token function">findLoadedClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                   <span class="token comment">//如果它的路径是以xxx开头的，我们就不委托父类加载器加载，而是我们自己加载</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>name<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"com.van.demo.test"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// If still not found, then invoke findClass in order</span>
                        <span class="token comment">// to find the class.</span>
                        <span class="token keyword">long</span> t1 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                        c <span class="token operator">=</span> <span class="token function">findClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>

                        sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">PerfCounter</span><span class="token punctuation">.</span><span class="token function">getFindClassTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addElapsedTimeFrom</span><span class="token punctuation">(</span>t1<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span><span class="token class-name">PerfCounter</span><span class="token punctuation">.</span><span class="token function">getFindClasses</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                     <span class="token comment">//其他的继续委托父类加载器加载，保持双亲委派</span>
                        c <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                <span class="token punctuation">&#125;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>resolve<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token function">resolveClass</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">return</span> c<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">private</span> <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">loadByte</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
            name <span class="token operator">=</span> name<span class="token punctuation">.</span><span class="token function">replaceAll</span><span class="token punctuation">(</span><span class="token string">"\\."</span><span class="token punctuation">,</span> <span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">FileInputStream</span> fis <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileInputStream</span><span class="token punctuation">(</span>classPath <span class="token operator">+</span> <span class="token string">"/"</span> <span class="token operator">+</span> name
                    <span class="token operator">+</span> <span class="token string">".class"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">int</span> len <span class="token operator">=</span> fis<span class="token punctuation">.</span><span class="token function">available</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> data <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">byte</span><span class="token punctuation">[</span>len<span class="token punctuation">]</span><span class="token punctuation">;</span>
            fis<span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
            fis<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> data<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">//重写findClass()方法</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">findClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span> <span class="token punctuation">&#123;</span>

            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> data <span class="token operator">=</span> <span class="token function">loadByte</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">//defineClass将一个字节数组转为Class对象，这个字节数组是class文件读取后最终的字节数组。</span>
                <span class="token keyword">return</span> <span class="token function">defineClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> data<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> data<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>


        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">IllegalAccessException</span><span class="token punctuation">,</span> <span class="token class-name">InstantiationException</span><span class="token punctuation">,</span> <span class="token class-name">NoSuchMethodException</span><span class="token punctuation">,</span> <span class="token class-name">InvocationTargetException</span> <span class="token punctuation">&#123;</span>

        <span class="token class-name">MyClassLoader</span> myClassLoader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token string">"d:/test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> aClass <span class="token operator">=</span> myClassLoader<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token string">"com.van.demo.test.Test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">ClassLoader</span> classLoader <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"classLoader = "</span> <span class="token operator">+</span> classLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Object</span> obj <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Method</span> method <span class="token operator">=</span> aClass<span class="token punctuation">.</span><span class="token function">getDeclaredMethod</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        method<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>



    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>此时我们的Test.class文件在当前项目的类路径下有一份，在自定义类加载器的路径下也有一份，如图：</p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/dfoyut"><img src="https://s1.ax1x.com/2020/08/27/dfoyut.png" alt="dfoyut.png" style="zoom:50%;" /></a></p>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/dfo6DP"><img src="https://s1.ax1x.com/2020/08/27/dfo6DP.md.png" alt="dfo6DP.md.png" style="zoom:50%;" /></a></p>
<p>如果遵循双亲委派机制，那么当前加载这个类的类加载器应该是AppClassLoader，但是最后的结果是：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">classLoader <span class="token operator">=</span> com<span class="token punctuation">.</span>van<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>sample<span class="token punctuation">.</span><span class="token class-name">MyClassLoaderTest</span>$<span class="token class-name">MyClassLoader</span><span class="token annotation punctuation">@449b2d27</span>
用自定义类加载器加载的<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>当前加载这个类的类加载器是MyClassLoader。这样，我们就打破了类加载器的双亲委派机制。</p>
<p>最后，解释一下，为什么我在重写loadClass()方法时，要根据路径判断，如果是指定路径下，就直接加载，如果不是这个路径下的，我们还是用双亲委派机制？因为<strong>java中所有的类都会继承自Obeject类，如果不加判断，全部都用当前自定义类加载器去加载，肯定会加载失败</strong>。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">van.shu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://van14.gitee.io/2020/08/21/bai-hua-jvm-1-lei-de-jia-zai-ji-zhi/">http://van14.gitee.io/2020/08/21/bai-hua-jvm-1-lei-de-jia-zai-ji-zhi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">van.shu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/jvm/">
                                    <span class="chip bg-color">jvm</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="far fa-dot-circle"></i>&nbsp;本篇
            </div>
            <div class="card">
                <a href="/2020/08/21/bai-hua-jvm-1-lei-de-jia-zai-ji-zhi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="白话JVM(1)-类的加载机制">
                        
                        <span class="card-title">白话JVM(1)-类的加载机制</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-08-21
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            van.shu
                            
                        </span>
                    </div>
                </div>

                
                <div class="card-action article-tags">
                    
                    <a href="/tags/jvm/">
                        <span class="chip bg-color">jvm</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/08/20/first-blog/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="first blog">
                        
                        <span class="card-title">first blog</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            这是 vanshu 的第一篇 blog
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-08-20
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            van.shu
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/hello/">
                        <span class="chip bg-color">hello</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='true'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="/libs/aplayer/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2021</span>
            
            <a href="/about" target="_blank">van.shu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1181062873@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1181062873" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1181062873" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
